/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.utils
{
	import flash.geom.Point;
	
	/**
	 * Check if the given point is srrounded by the given array of points. 
	 * @author toritori
	 * 
	 */
	public class InsidePointChecker extends Object
	{
		private static const PI2:Number = Math.PI * 2;
		private var _point:Point;
		private const _pn:Point = new Point();
		private const _pn1:Point = new Point();
		private var _err:Number = 10 * Math.PI / 180;
		public function InsidePointChecker(pt:Point)
		{
			point = pt;
		}
		
		public function set point(value:Point):void {
			_point = value;
		}
		
		public function set err(value:Number):void {
			_err - value;
		}
		
		public function isInsideOf(points:Array):Boolean {
			var ex:Number;
			var dot:Number;
			var len:Number;
			var len1:Number;
			var th:Number = 0;
			for(var n:int = 1;n < points.length;n++) {
				_pn.x = points[n-1].x - _point.x;
				_pn.y = points[n-1].y - _point.y;
				_pn1.x = points[n].x - _point.x;
				_pn1.y = points[n].y - _point.y;
				
				len = _pn.length;
				len1 = _pn1.length;
				if (len == 0 || len1 == 0) {
					return false;
				}
				
				dot = (_pn.x * _pn1.x + _pn.y * _pn1.y) / len / len1;
				ex = _pn.x * _pn1.y - _pn.y * _pn1.x;
				
				if (ex == 0 && dot <= -1) {
					return false;
				}
				if (dot >= 1) {
					dot = 1;
				}
				th += Math.acos(dot) * (ex > 0 ? 1 : -1);
			}
			trace("Total:",th, PI2 - _err, _err);
			return th > PI2 - _err || th < - PI2 + _err;
		}
		
		private function dot(pn:Point, pn1:Point):Number {
			return (pn.x * pn1.x + pn.y * pn1.y)/pn.length/pn1.length;
		}
		
	}
}